<?php
namespace app\index\controller;

use app\index\Controller;
use think\Db;

class Sell extends Controller
{
    //初始化
    public function _initialize()
    {
        parent::_initialize();
        $this->timeout(); //触发超时订单处理
    }

    //挂售
    public function sell()
    {
        $config = config('currency');
        if($this->request->isPost()){
            $post = $this->request->post();
            if (empty($this->user['alipay']) && empty($this->user['bank_card'])) {
                return json(['success' => 0, 'msg' => '请先完善财务信息', 'url' => '/user/info']);
            }
            //判断倍数
            if($post['money'] % $config['minMoney'] != 0){
                return json(['success' => 0, 'msg' => '挂售数量不是'.$config['minMoney'].'的倍数']);
            }
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            //判断余额
            if ($this->user['money'] < $post['money']) {
                return json(['success' => 0, 'msg' => $config['money'] . '余额不足']);
            }
            //计算手续费
            $fee = sprintf("%.2f", $config['sellFee'] / 100 * $post['money']);
            //应付金额
            $money = sprintf("%.2f", $post['money'] - $fee);
            //扣提现币
            $message = "申请挂售支出 {$post['money']} 元";
            $result  = dec_money($this->user['id'], $this->user['username'], 'money', $post['money'], $message, 10);
            if (!$result) {
                return json(['success' => 0, 'msg' => '挂售失败，请重试']);
            }
            //添加记录
            Db::name('sell')->insert([
                'user_id'     => $this->user['id'],
                'username'    => $this->user['username'],
                'money'       => $money,
                'fee'         => $fee,
                'note'        => $post['note'],
                'time' => time(),
            ]);
            return json(['success' => 1, 'msg' => '申请挂售成功', 'url' => '/mySell']);
        }else{
            $this->setPayPwd($this->request->url(true));
            $this->assign('config',$config);
            return $this->fetch();
        }
    }

    //挂售记录
    public function mySell()
    {
        $list = Db::name('sell')->where('user_id', $this->user['id'])->order('id desc')->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //撤销挂售
    public function revoke()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $row = Db::name('sell')->find($post['id']);
            //挂售不存在或已是撤销状态或不是当前用户
            if(!$row || $row['status'] == 4 || $row['user_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            //修改状态
            $result = Db::name('sell')->update(['id'=>$row['id'],'status'=>4]);
            //退款
            if($result){
                $money = $row['money'] + $row['fee'];
                if(inc_money($row['user_id'], $row['username'], 'money', $money, '挂售ID: '.$row['id'].' 撤销退款', 11)){
                    return json(['success' => 1, 'msg' => '撤销成功']);
                }
            }
            return json(['success' => 0, 'msg' => '撤销失败，请重试']);
        }
    }

    //确认
    public function confirm()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $row = Db::name('sell')->find($post['id']);
            //挂售不存在或已是确认状态或不是当前用户
            if(!$row || $row['status'] == 3 || $row['user_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            //修改状态
            $result = Db::name('sell')->update(['id'=>$row['id'],'status'=>3]);
            //给代理充值
            if($result){
                $agent = Db::name('user')->find($row['agent_id']);
                if($agent){
                    $config = config('currency');
                    $reward = sprintf("%.2f", $row['money'] - ($config['rebate'] / 10 * $row['money'])); //返利
                    inc_money($agent['id'], $agent['username'], 'recharge', $row['money'], '挂售ID: '.$row['id'].' 充值到账', 5);
                    inc_money($agent['id'], $agent['username'], 'recharge', $reward, '挂售ID: '.$row['id'].' 接单奖励', 12);
                    return json(['success' => 1, 'msg' => '确认成功']);
                }
            }
            return json(['success' => 0, 'msg' => '操作失败，请重试']);
        }
    }

    //代理接单列表
    public function orders()
    {
        if(!$this->user['agent']){
            $this->redirect('/user');
        }
        $this->setPayPwd($this->request->url(true));
        $list = Db::name('sell')->where('status', 0)->order('rand()')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //接单
    public function addOrder()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $row = Db::name('sell')->find($post['id']);
            //挂售不存在或不是未接单状态
            if(!$row || $row['status'] != 0){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            //修改状态
            $config = config('currency');
            $result = Db::name('sell')->update([
                'id' => $row['id'],
                'agent_id' => $this->user['id'],
                'timeout' => time() + $config['payTimeout'],
                'status' => 1
            ]);
            if(!$result){
                return json(['success' => 0, 'msg' => '操作失败，请重试']);
            }
            return json(['success' => 1, 'msg' => '操作成功']);
        }
    }

    //我的订单
    public function myOrders()
    {
        $this->setPayPwd($this->request->url(true));
        $list = Db::view('sell','*')
        ->view('user','qq,mobile,wechat,email,alipay,bank,bank_card,realname','user.id=sell.user_id')
        ->where('agent_id', $this->user['id'])
        ->order('timeout DESC')
        ->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //代理撤销订单
    public function cancelOrder()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $row = Db::name('sell')->find($post['id']);
            //挂售不存在或已经是撤销状态或者不是当前用户
            if(!$row || $row['status'] == 4 || $row['agent_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            //扣违约金
            $config = config('currency');
            if($config['cancelPunish'] > 0){
                $agent = Db::name('user')->find($row['agent_id']);
                dec_money($agent['id'],$agent['username'],'money',$config['cancelPunish'],'取消订单ID：'.$row['id'].' 扣除违约金',13);
            }
            //补偿挂售人
            if($config['cancelReward'] > 0){
                inc_money($row['user_id'],$row['username'],'money',$config['cancelReward'],'接单人取消订单ID：'.$row['id'].' 获得系统补偿',14);
            }
            //重新挂售
            $result = Db::name('sell')->update([
                'id' => $row['id'],
                'agent_id' => 0,
                'time' => time(),
                'timeout' => 0,
                'status' => 0
            ]);
            if(!$result){
                return json(['success' => 0, 'msg' => '取消订单失败']);
            }
            return json(['success' => 1, 'msg' => '取消订单成功']);
        }
    }

    //代理确认支付
    public function confirmPay()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $row = Db::name('sell')->find($post['id']);
            //挂售不存在或已经是已支付状态或者不是当前用户
            if(!$row || $row['status'] == 3 || $row['agent_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            $config = config('currency');
            //修改状态
            $result = Db::name('sell')->update([
                'id' => $row['id'],
                'status' => 2,
                'timeout' => time() + $config['payTimeout']
            ]);
            if(!$result){
                return json(['success' => 0, 'msg' => '操作失败，请重试']);
            }
            return json(['success' => 1, 'msg' => '操作成功']);
        }
    }

    //处理超时订单
    private function timeout()
    {
        $config = config('currency');
        //代理已接单状态超时，扣违约金，补偿卖家，重新挂售
        $sell1 = Db::name('sell')->where(['status'=>1,'timeout'=>['lt',time()]])->select();
        if($sell1){
            foreach ($sell1 as $row) {
                //扣违约金
                if($config['timeoutPunish'] > 0){
                    $agent = Db::name('user')->find($row['agent_id']);
                    dec_money($agent['id'],$agent['username'],'money',$config['timeoutPunish'],'订单ID：'.$row['id'].' 支付超时扣除违约金',15);
                }
                //补偿挂售人
                if($config['timeoutReward'] > 0){
                    inc_money($row['user_id'],$row['username'],'money',$config['timeoutReward'],'订单ID：'.$row['id'].' 超时补偿',16);
                }
                //重新挂售
                Db::name('sell')->update([
                    'id' => $row['id'],
                    'agent_id' => 0,
                    'time' => time(),
                    'timeout' => 0,
                    'status' => 0
                ]);
            }
        }
        //卖家确认收款状态超时，交易自动完成，给代理充值，并返利
        $sell2 = Db::name('sell')->where(['status'=>2,'timeout'=>['lt',time()]])->select();
        if($sell2){
            foreach ($sell2 as $row) {
                Db::name('sell')->update([
                    'id' => $row['id'],
                    'status' => 3
                ]);
                $agent = Db::name('user')->find($row['agent_id']);
                if($agent){
                    $reward = sprintf("%.2f", $row['money'] - ($config['rebate'] / 10 * $row['money'])); //返利
                    inc_money($agent['id'], $agent['username'], 'recharge', $row['money'], '挂售ID: '.$row['id'].' 充值到账', 5);
                    inc_money($agent['id'], $agent['username'], 'recharge', $reward, '挂售ID: '.$row['id'].' 接单奖励', 12);
                }
            }
        }
    }
}
